package org.aiforum.backend.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aiforum.backend.common.AdminHelper;
import org.aiforum.backend.common.CookieHelper;
import org.aiforum.backend.common.RequestHelper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限认证拦截器
 * 1. 拦截所有控制器请求(除登录功能和验证码请求)
 * 2. 如果管理员没有登录成功,则进入登录页登录
 * 3. 如果管理员没有权限操作,则进入消息页面提示
 * @author JAVA
 *
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求URL(和权限路径及控制器路径相对应)
		String url = RequestHelper.getRequestPath(request);
		// 获取token
		String token = CookieHelper.getCookie("token", request);
		// 获取项目根路径
		String rootPath = request.getContextPath();
		// 如果管理员没有登录成功,则进入登录页登录
		if(!AdminHelper.hasLogin(token)){
			//重定向到登录页
			response.sendRedirect(rootPath + "/login");
			return false;
		}
		// 如果管理员没有权限操作,则进入消息页面提示
		if(!AdminHelper.hasAuthOperate(token,url)){
			
			response.sendRedirect(rootPath + "/message?message=sorry! your not auth operate.");
			return false;
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
